package com.xiaobai.netease_news.activities;


import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.xiaobai.netease_news.R;
import com.xiaobai.netease_news.adapters.TopNewsAdapter;
import com.xiaobai.netease_news.constants.Constant;
import com.xiaobai.netease_news.model.ResponseData;
import com.xiaobai.netease_news.utils.CommonHttpUtil;
import com.xiaobai.netease_news.views.CircleProgressBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class TopNewsActivity extends Activity
        implements SwipeRefreshLayout.OnRefreshListener,
        AbsListView.OnScrollListener, View.OnClickListener, AdapterView.OnItemClickListener {

    private LinearLayout topNewsLoadingMore;
    private boolean isBottom;
    private SwipeRefreshLayout topNewsRefresh;
    private List<ResponseData> responseDatas;
    private TopNewsAdapter adapter;
    private int i = 1;
    private CircleProgressBar loadingProgress;
    private boolean isProgressBarShow;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_top_news);

        responseDatas = new ArrayList<>();
        adapter = new TopNewsAdapter(this, responseDatas);

        new NewsListTask().execute(Constant.TODAY_TOP_NEWS, "0");

        topNewsRefresh = (SwipeRefreshLayout) findViewById(R.id.top_news_swipe_refresh);
        ListView topNewsList = (ListView) topNewsRefresh.findViewById(R.id.item_list);
        topNewsLoadingMore = (LinearLayout) findViewById(R.id.top_news_loading_layout);

        topNewsRefresh.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        topNewsRefresh.setOnRefreshListener(this);

        topNewsList.setAdapter(adapter);
        topNewsList.setOnScrollListener(this);
        topNewsList.setOnItemClickListener(this);

        loadingProgress = (CircleProgressBar) findViewById(R.id.top_news_loading);
        if (!isProgressBarShow)
            loadingProgress.setVisibility(View.VISIBLE);
        else
            loadingProgress.setVisibility(View.GONE);
        isProgressBarShow = true;

        ImageView back = (ImageView) findViewById(R.id.top_news_back);
        back.setOnClickListener(this);

    }

    @Override
    public void onRefresh() {
        // TODO 刷新数据
        new NewsListTask().execute(Constant.TODAY_TOP_NEWS, "0");
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (isBottom && scrollState == SCROLL_STATE_IDLE) {
            topNewsLoadingMore.setVisibility(View.VISIBLE);
            // TODO 加载更多数据
            new NewsListTask().execute(Constant.TODAY_TOP_NEWS, (i * 20) + "");
            i++;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        isBottom = (firstVisibleItem + visibleItemCount) == totalItemCount;
    }

    @Override
    public void onClick(View v) {
        this.finish();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ResponseData responseData = responseDatas.get(position);
        String url_3w = responseData.getUrl_3w();
        Intent intent = new Intent(this, NewsDetailActivity.class);
        intent.putExtra("replyCount", responseData.getReplyCount());
        intent.putExtra("title", responseData.getTitle());
        intent.putExtra("source", responseData.getSource());
        intent.putExtra("ptime", responseData.getPtime());
        intent.putExtra("url_3w", url_3w);
        startActivity(intent);
    }

    private class NewsListTask extends AsyncTask<String, Void, JSONObject> {
        private String _id = null;
        private String num = null;

        @Override
        protected JSONObject doInBackground(String... params) {

            _id = params[0];
            num = params[1];
            String url = "http://c.3g.163.com/nc/article/list/" + params[0] + "/" + params[1] + "-20.html";

            byte[] bytes = CommonHttpUtil.doGet(url);
            if (bytes != null) {
                try {
                    String jsonString = new String(bytes, "utf-8");
                    return new JSONObject(jsonString);
                } catch (UnsupportedEncodingException | JSONException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {

            if (loadingProgress.getVisibility() == View.VISIBLE)
                loadingProgress.setVisibility(View.GONE);

            topNewsRefresh.setRefreshing(false);
            topNewsLoadingMore.setVisibility(View.GONE);

            if (jsonObject != null) {
                List<ResponseData> datas = new ArrayList<>();

                try {
                    JSONArray jsonArray = jsonObject.getJSONArray(_id);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        ResponseData responseData = new ResponseData();
                        responseData.parseJson(object);

                        datas.add(responseData);
                    }

                    if (num.equals("0")) {
                        responseDatas.clear();
                        responseDatas.addAll(0, datas);
                    } else
                        responseDatas.addAll(datas);

                    adapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}
